package com.example.juctest.queue_test;

import lombok.SneakyThrows;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author 28116
 */
public class MyArrayBlockingQueueTest {

    private static final ArrayBlockingQueue<Integer> QUEUE = new ArrayBlockingQueue<>(10);

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 100; i++) {
            addElement(i);
        }

    }

    public static synchronized void addElement(Integer integer) throws InterruptedException {
        boolean isFull = isFull();
        int count = QUEUE.size() >> 1;
        if (isFull) {
            for (int i = 0; i < count; i++) {
                QUEUE.poll();
            }
        }
        QUEUE.put(integer);
    }

    public static boolean isFull() {
        return QUEUE.size() == 10;
    }

    public static class Main {


        public static void main(String[] args) throws InterruptedException {
            SellTicket sellTicket = new SellTicket();
            Thread.sleep(100);
            Thread t1 = new Thread(sellTicket);
            Thread t2 = new Thread(sellTicket);
            t1.start();
            t2.start();
            // t1.start();
        }

    }

    static class SellTicket implements Runnable {

        private static int total = 100;

        @SneakyThrows
        @Override
        public synchronized void run() {
            while (total > 0) {
                System.out.println(Thread.currentThread().getName() + " ===开始卖票===");
                Thread.sleep(10);
                total--;
                System.out.println("剩余" + total + "张票");
            }
        }
    }
}
